package com.xique.door.biz.service.impl;


import com.xique.common.core.text.Convert;
import com.xique.common.core.utils.StringUtils;
import com.xique.common.core.web.domain.AjaxResult;
import com.xique.door.bean.domain.*;
import com.xique.door.bean.request.commandV1.DeviceCommandAddDevicesRequest;
import com.xique.door.bean.request.commandV1.DeviceCommandDelDevicesRequest;
import com.xique.door.bean.request.permissionGroup.PermissionGroupDeleteDeviceRequest;
import com.xique.door.bean.request.permissionGroup.PermissionGroupDeviceRequest;
import com.xique.door.bean.request.permissionGroup.PermissionGroupSelectDeviceRequest;
import com.xique.door.biz.service.IDeviceCommandNewService;
import com.xique.door.biz.service.IPermissionGroupDeviceBizService;
import com.xique.door.constant.AccessCommandConstant;
import com.xique.door.constant.AccessDeviceConstant;
import com.xique.door.device.hk.bean.response.BasicResponse;
import com.xique.door.device.hk.bean.response.PermissionGroupResponse;
import com.xique.door.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * @author shd
 * @create 2021/7/3 8:54
 */
@Service
@Deprecated
public class PermissionGroupDeviceBizServiceImpl implements IPermissionGroupDeviceBizService {

    @Autowired
    private IPermissionGroupUserService permissionGroupUserService;

    @Autowired
    private IPermissionGroupDomainService permissionGroupDomainService;

    @Autowired
    private IAccessDeviceService accessDeviceService;

    @Autowired
    private IDeviceCommandNewService deviceCommandNewService;

    @Autowired
    private IPermissionGroupService permissionGroupService;

    @Autowired
    private IPermissionGroupDeviceService permissionGroupDeviceService;

    /**
     * 删除设备
     * @author shd
     * @date 2021/7/7 15:51
     * @param request
     * @return com.ruoyi.common.core.domain.AjaxResult
     * 1.删除权限组设备 2.删除用户设备 3.下发删除信息到设备
     */
    @Override
    public AjaxResult deleteDevice(PermissionGroupDeleteDeviceRequest request) {

        List<Long> deviceIds = Collections.singletonList(request.getDeviceId());

        DeviceCommandDelDevicesRequest deviceCommandDelDevicesRequest = new DeviceCommandDelDevicesRequest();
        deviceCommandDelDevicesRequest.setGroupId(request.getGroupId());
        deviceCommandDelDevicesRequest.setDeviceIds(deviceIds);
        deviceCommandNewService.permissionDelDevices(deviceCommandDelDevicesRequest);

        //TODO 下发设备删除信息
        int count = permissionGroupDomainService.deleteDevice(request.getGroupId(), deviceIds);
        if (count <= 0) {
            return AjaxResult.error("删除失败");
        }

        return AjaxResult.success("删除完成！设备命令已下发，具体下发状态请查看设备下发状态列表");
    }

    /**
     * 批量删除设备
     * @author shd
     * @date 2021/7/7 15:51
     * @param request
     * @return com.ruoyi.common.core.domain.AjaxResult
     * 1.删除权限组设备 2.删除用户设备 3.下发删除信息到设备
     */
    @Override
    public AjaxResult deleteDevices(PermissionGroupDeleteDeviceRequest request) {

        List<Long> deviceIds = Arrays.asList(Convert.toLongArray(request.getDeviceIds()));
        Long groupId = request.getGroupId();

        DeviceCommandDelDevicesRequest deviceCommandDelDevicesRequest = new DeviceCommandDelDevicesRequest();
        deviceCommandDelDevicesRequest.setGroupId(groupId);
        deviceCommandDelDevicesRequest.setDeviceIds(deviceIds);
        deviceCommandNewService.permissionDelDevices(deviceCommandDelDevicesRequest);

        //TODO 下发设备删除信息
        int count = permissionGroupDomainService.deleteDevice(groupId, deviceIds);
        if (count <= 0) {
            return AjaxResult.error("删除失败");
        }

        return AjaxResult.success("删除完成！设备命令已下发，具体下发状态请查看设备下发状态列表");
    }

    /**
     * 权限组添加设备
     * @author shd
     * @date 2021/7/8 14:21
     * @param request
     * @return com.ruoyi.common.core.domain.AjaxResult
     * 1.添加权限组设备 2.添加用户设备 3.下发信息到设备
     */
    @Override
    public AjaxResult addDevices(PermissionGroupSelectDeviceRequest request) {
        Long groupId = request.getGroupId();
        List<Long> deviceIds = Arrays.asList(Convert.toLongArray(request.getDeviceIds()));

        List<PermissionGroupDevice> deviceList = new ArrayList<>();
        deviceIds.forEach(item -> {
            PermissionGroupDevice groupDevice = new PermissionGroupDevice();
            groupDevice.setGroupId(groupId);
            groupDevice.setDeviceId(item);
            deviceList.add(groupDevice);
        });

        List<UserDevice> list = new ArrayList<>();
        List<PermissionGroupUser> permissionGroupUserList = permissionGroupUserService.selectPermissionGroupUserListByGroupIds(Collections.singletonList(groupId));
        List<AccessDevice> accessDeviceList = accessDeviceService.selectAccessDeviceByIds(deviceIds, AccessDeviceConstant.DeviceStatus.NORMAL);
        permissionGroupUserList.forEach(item -> {
            accessDeviceList.forEach(device -> {
                UserDevice userDevice = new UserDevice();
                userDevice.setParkId(request.getParkId());
                userDevice.setGroupId(groupId);
                userDevice.setUserId(item.getUserId());
                userDevice.setDeviceId(device.getId());
                userDevice.setDevSn(device.getDevSn());
                list.add(userDevice);
            });
        });

        long count = accessDeviceList.stream().filter(item -> AccessCommandConstant.DeviceType.HK.equals(item.getModel())).count();
        PermissionGroup permissionGroup = permissionGroupService.selectPermissionGroupById(request.getGroupId());
        if (count > 0 && StringUtils.isEmpty(permissionGroup.getHkGroupId())) {
            // 添加海康权限组
            PermissionGroupResponse response = deviceCommandNewService.addGroup(request.getGroupId());
            if (!BasicResponse.isSuccess(response) && !"40021002".equals(response.getCode())) {
                return AjaxResult.error("添加失败，请联系管理员");
            }
            PermissionGroup update = new PermissionGroup();
            update.setId(request.getGroupId());
            update.setHkGroupId(response.getData().getGroupId());
            permissionGroupService.updatePermissionGroup(update);
        }

        DeviceCommandAddDevicesRequest deviceCommandAddDevicesRequest = new DeviceCommandAddDevicesRequest();
        deviceCommandAddDevicesRequest.setGroupId(groupId);
        deviceCommandAddDevicesRequest.setDeviceIds(deviceIds);
        deviceCommandNewService.permissionAddDevices(deviceCommandAddDevicesRequest);

        boolean isSuccess = permissionGroupDomainService.addDevices(deviceList, list);
        if (!isSuccess) {
            return AjaxResult.error("添加失败");
        }

        //TODO 下发设备信息
//        List<Long> userIds = permissionGroupUserList.stream().map(PermissionGroupUser::getUserId).distinct().collect(Collectors.toList());
//        List<User> userList = userService.selectUserByIds(userIds, UserConstant.Status.NORMAL);
//        List<String> devSns = accessDeviceList.stream().map(AccessDevice::getDevSn).collect(Collectors.toList());
//
//        applicationContext.publishEvent(new AddDeviceBatchCommandEvent(devSns, userList));

        return AjaxResult.success("添加成功");
    }

    @Override
    public List<PermissionGroupDevice> selectUnallocatedList(PermissionGroupDeviceRequest request) {
        request.setStatus("normal");
        return permissionGroupDeviceService.selectUnallocatedList(request);
    }

    @Override
    public List<PermissionGroupDevice> selectAllocatedList(PermissionGroupDeviceRequest request) {
        return permissionGroupDeviceService.selectAllocatedList(request);
    }
}
